
// 套餐
import React, { useEffect, useState, useRef, useMemo, useCallback } from 'react';
import Header from '@/components/Header/Header';
import { useSelector, useDispatch, history } from 'umi';
import { queryPackage } from '@/services/order';
import Pic_Hold from '@/assets/images/pic_hold.png';
import NumberPicker from '@/components/NumberPicker/NumberPicker';

import { isEmpty } from '@/utils/common';
import SpecPicker from '../index/components/specPicker';

import numeral from 'numeral';
import { AsyncLoading, SwiperBox, Picture, Price, AffixBottom, Message } from '@/design'

import styles from './mainPack.less';

export default function (props: any) {
  const braId = localStorage.getItem('BRAID');
  const codeId = localStorage.getItem('CODEID');

  const [packageInfo, setPackageInfo] = useState<any>({});
  const swiperRef = useRef<HTMLDivElement>(null);
  let [specVisiable, setSpecVisiable] = useState<boolean>(false);

  let [curentDetailInfo, setCurentDetailInfo] = useState<any>({
    parentItem: {},
    packdetail: {}
  });
  const [images, setImages] = useState<any>([]);
  const { productId } = props.match.params;

  const [state, setState] = useState({
    choosePackageMap: new Map(), //选的品类
    choosePackageDetailsMap: new Map(),//选的所有detail
    choosePackageDetailsLengthMap: new Map() //每个品类选的总份数
  });
  const { cartList } = useSelector((state: any) => state.cartList);
  const { currentstore } = useSelector((state: any) => state.currentstore);


  const dispatch = useDispatch();

  useEffect(() => {
    fetchPackage();
  }, [productId]);

  useEffect(() => {
    fetchImages();
    fetchDefaultProductPackages();
  }, [packageInfo])

  const fetchPackage = async () => {
    let result = await queryPackage(productId);
    if (!result || !result.data) return;
    setPackageInfo(result.data);
  }

  // 获取详情
  const fetchDefaultProductPackages = () => {
    if (isEmpty(packageInfo)) return;
    let result: any = []; //默認激活必選的
    packageInfo.productPackages.forEach((item: any) => {
      if (item.packageType === 'M') {
        result.push(item)
      }
    });
    let newChoosePackageMap = state.choosePackageMap;
    let newChoosePackageDetailsMap = state.choosePackageDetailsMap;
    let newChoosePackageDetailsLengthMap = state.choosePackageDetailsLengthMap;

    result.forEach((item: any) => {
      newChoosePackageMap.set(item.packageId, item);
      newChoosePackageDetailsLengthMap.set(item.packageId, item.packageDetails.length);
      item.packageDetails.forEach((detail: any) => {
      const { packageId, adjustPrice, categoryId, categoryName , productName, quantity, productId} = detail;
        let packdetail = {
          packageId,
          adjustPrice,
          categoryId,
          categoryName,
          productQuantity: 1,
          productId,
          productName,
          quantity,
        };
        newChoosePackageDetailsMap.set(detail.detailId, packdetail)
      })
    })
    setState({
      ...state,
      choosePackageMap: newChoosePackageMap,
      choosePackageDetailsMap: newChoosePackageDetailsMap,
      choosePackageDetailsLengthMap: newChoosePackageDetailsLengthMap
    });
  }

  // banner
  const fetchImages = () => {
    if (isEmpty(packageInfo)) return;
    const { productIcon1, productIcon2, productIcon3 } = packageInfo;
    let imgs = getImages([productIcon1, productIcon2, productIcon3]);
    imgs = imgs.length ? imgs : [Pic_Hold]
    setImages(imgs)
  }

  // 套餐的描述
  const packagetDesc = useMemo(() => {
    let res: any = [];
    if (isEmpty(packageInfo.productPackages)) return ''
    packageInfo.productPackages.forEach((item: any) => {
      const packageTypeDesc = item.packageType === 'M' ? '必選' : '可選';
      res.push(`【${item.packageContent}】(${packageTypeDesc}${item.optionalQuantity}份)`);
    })
    return res
  }, [packageInfo.productPackages]);

  // 处理返回的图片成数组
  const getImages = (arr: any[]) => {
    const arrTemp = arr.reduce((acc, val) => {
      if (val) {
        acc.push(`${val}/600`);
      }
      return acc
    }, []);
    return arrTemp.length ? arrTemp : [Pic_Hold]
  }

  // 已选
  const getSelectedDesc = (item: any) => {
    let res: any = [];
    const { packageId } = item;
    let chooseDetailArray: any = [...state.choosePackageDetailsMap.values()];
    chooseDetailArray.forEach((item: any) => {
      if (item.packageId === packageId) {
        if (!isEmpty(item.tasteList)) {
          let amount: number = 0;
          item.tasteList.forEach((o: any) => {
            amount += o.price * o.num;
          });
          let totalAmount = amount * item.quantity;
          res.push(`[${item.productName}]${item.quantity}份 (${chooseTasteIds(item.tasteList)} ${amount > 0 ? `+NT$${amount}` : ''})${totalAmount > 0 ? `,共NT$${totalAmount}` : ''}`)
        } else {
          res.push(`[${item.productName}]${item.quantity}份`)
        }
      }
    })
    return res;
  }

  // 计算价格
  const calcPrice = useCallback(() => {
    const { productPrice } = packageInfo;
    let numTotal: number = 0;
    if (!isEmpty(packageInfo)) {
      numTotal = numeral(productPrice).value();
    }
    let chooseArray = [...state.choosePackageDetailsMap.values()];
    if (!isEmpty(chooseArray)) {
      chooseArray.forEach((item: any) => {
        if (!isEmpty(item.tasteList)) {
          item.tasteList.forEach((taste: any) => {
            let thisAmount = numeral(taste.num).multiply(taste.price).value();
            thisAmount = numeral(thisAmount).multiply(item.quantity).value();
            numTotal = numeral(numTotal || 0).add(thisAmount).value();
          });
        }
      })
    }
    return numTotal
  }, [state.choosePackageMap, packageInfo])

  // 点击已选好
  const handleChooseOk = () => {
    const { productIcon1, productId, productPrice, productQuantity, productName, productPackages } = packageInfo;
    // 根據state的map信息整合已選的   
    let newChoosePackageDetailsLengthMap = state.choosePackageDetailsLengthMap;
    let newChoosePackageDetailsMap = state.choosePackageDetailsMap;
    let newChoosePackageMap = state.choosePackageMap;
    let choosePackIds = [...newChoosePackageMap.keys()];
    for (let i = 0; i < choosePackIds.length; i++) {//攔截已選的選不夠
      let optionalQuantity = newChoosePackageMap.get(choosePackIds[i]).optionalQuantity;
      let needChooseQuantity = newChoosePackageDetailsLengthMap.get(choosePackIds[i])
      if (Number(optionalQuantity) !== Number(needChooseQuantity)) {
        console.log('需选的不够', newChoosePackageMap.get(choosePackIds[i]))
        return Message.error(`請選擇${newChoosePackageMap.get(choosePackIds[i]).packageContent}`)
      }
    }
    if (productPackages.length !== choosePackIds.length) {//攔截需要選的沒選
      let notChoosePackageIds: any = [];//找出必選當中沒有選擇的Id
      let allPackageIds = productPackages.map((item: any) => item.packageId);
      notChoosePackageIds = allPackageIds.filter((item: any) => {
        return choosePackIds.indexOf(item) === -1
      });
      for (let i = 0; i < notChoosePackageIds.length; i++) {//顯示沒選的packId name
        let res = productPackages.filter((item: any) => {
          return item.packageId === notChoosePackageIds[i]
        })
        let name = res.length ? res[0].packageContent : '';
        return Message.error(`請選擇${name}`);
      }
    }
    // 所有的detail分类下
    let res = [...newChoosePackageDetailsMap.values()].reduce((m: any, n: any) => {
      if (!m[n.packageId]) {
        m[n.packageId] = []
      }
      m[n.packageId].push(n)
      return m
    }, {});

    let newProductPackages = [...newChoosePackageMap.values()].map((({ braId, optionalQuantity, optionalRepeat, packageContent, packageId, packageType }: any) => {
      return {
        braId,
        optionalQuantity,
        optionalRepeat,
        packageContent,
        packageDetails: res[packageId],
        packageId,
        packageType,
        productId,
        productName,
      }
    }));
    // z这些参数放到购物车
    let param = {
      productIcon: productIcon1,
      productId,
      productName,
      productPackages: newProductPackages,
      tasteList: [],
      productQuantity: 1,
      productPrice
    };
    let newCartList = JSON.parse(JSON.stringify(cartList));
    newCartList.push(param);
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    });
    history.push(`/home?braId=${braId}&codeId=${codeId}`);
  }

  //taste remark
  const chooseTasteIds = (tasteList: any) => {
    let str: any = [];
    tasteList.forEach((o: any) => {
      str.push(`${o.tasteName}X${o.num}份`)
    })
    return str.join('/')
  }

  //激活class
  const activeClassName = (packdetail: any, item: any) => {
    const { detailId } = packdetail;
    let res = '';
    if (state.choosePackageDetailsMap.has(detailId)) return styles.active
    return res;
  }

  const handleClickItem = (parentItem: any, packdetail: any) => {
    const { packageId, optionalQuantity, packageContent, packageType } = parentItem;
    const { detailId, tasteCategoryList, productStatus } = packdetail;
    if (productStatus === 2) {
      return Message.error('商品已售空！')
    }
    if (packageType === 'M') return //
    setCurentDetailInfo({
      parentItem,
      packdetail
    });//设置当前的packdetail

    let newChoosePackageDetailsLengthMap = state.choosePackageDetailsLengthMap;
    let newChoosePackageDetailsMap = state.choosePackageDetailsMap;
    let newChoosePackageMap = state.choosePackageMap;
    if (newChoosePackageDetailsMap.has(detailId)) {//判断是否有当前的detailId
      if (newChoosePackageMap.has(packageId)) {
        if(optionalQuantity === 1) {//只选一个
          let length = newChoosePackageDetailsLengthMap.get(packageId);
          let currentDetail = newChoosePackageDetailsMap.get(detailId);
          if(currentDetail.quantity > 1) {
            newChoosePackageDetailsLengthMap.set(packageId, currentDetail.quantity - 1);
            newChoosePackageDetailsMap.set(detailId, {
              ...currentDetail,
              quantity: currentDetail.quantity - 1
            })
          } else {
            newChoosePackageDetailsLengthMap.set(packageId, length - 1);
            newChoosePackageDetailsMap.delete(detailId)
          }
          if (length === 1) {
            newChoosePackageMap.delete(packageId);
          }
        } else {//可选的大于1
          if(newChoosePackageDetailsLengthMap.get(packageId) < optionalQuantity) {
            if (isEmpty(tasteCategoryList)) {
              let currentDetail = newChoosePackageDetailsMap.get(detailId);
              newChoosePackageDetailsLengthMap.set(packageId, currentDetail.quantity + 1);
              newChoosePackageDetailsMap.set(detailId, {
                ...currentDetail,
                quantity:currentDetail.quantity + 1});
            } else {
              setSpecVisiable(true);
            }
          }
        }
      }
    } else {
      if (newChoosePackageDetailsLengthMap.get(packageId) >= optionalQuantity) {
        Message.error(`${packageContent}超出可選數量`);
        return false;
      }

      if (isEmpty(tasteCategoryList)) {
        newChoosePackageDetailsMap.set(detailId, packdetail);
        newChoosePackageMap.set(packageId, packdetail);
        let length = newChoosePackageDetailsLengthMap.get(packageId) || 0;
        newChoosePackageDetailsLengthMap.set(packageId, length + 1);
      } else {
        setSpecVisiable(true);
      }
    }


    setState({
      ...state,
      choosePackageMap: newChoosePackageMap,
      choosePackageDetailsLengthMap: newChoosePackageDetailsLengthMap,
      choosePackageDetailsMap: newChoosePackageDetailsMap
    })
  }

  const onClickSure = (tasteList: any) => {
    let newChoosePackageMap = state.choosePackageMap;
    let newChoosePackageDetailsLengthMap = state.choosePackageDetailsLengthMap;
    let newChoosePackageDetailsMap = state.choosePackageDetailsMap;
    let { packdetail, parentItem } = curentDetailInfo;
    const { packageId, optionalQuantity, packageContent, packageType } = parentItem;
    const { detailId, adjustPrice, categoryId, categoryName, productId, productName } = packdetail;
    let param = {
      packageId,
      adjustPrice,
      categoryId,
      categoryName,
      perquantity: 1,
      productId,
      productName,
      quantity: 1,
      tasteList
    }
    if(newChoosePackageDetailsMap.has(detailId)) {
      console.log('有的時候', newChoosePackageDetailsMap.get(detailId))
      if(Array.isArray(newChoosePackageDetailsMap.get(detailId))) {
        newChoosePackageDetailsMap.get(detailId).push(param)
        newChoosePackageDetailsMap.set(`${detailId}`,  newChoosePackageDetailsMap.get(detailId));
      }
    } else {
      newChoosePackageDetailsMap.set(`${detailId}`, [param]);
    }
   
    let length = newChoosePackageDetailsLengthMap.get(packageId) || 0;
    newChoosePackageDetailsLengthMap.set(packageId, length + 1);
    newChoosePackageMap.set(packageId, parentItem)
    setState({
      ...state,
      choosePackageMap: newChoosePackageMap,
      choosePackageDetailsLengthMap: newChoosePackageDetailsLengthMap,
      choosePackageDetailsMap: newChoosePackageDetailsMap
    })
    setSpecVisiable(false);
  }

  // 相同的package的个数
  const reducePackageLength = (array: any, packageId: any) => {
    console.log('reducePackageLength')
    let num = 0;
    array.forEach((item: any) => {
      if (item.packageId === packageId) {
        if(Array.isArray(item)) {
          console.log('chulixai', item)
        }else {
          num += item.quantity
        }
       
      }
    });
    return num;
  }

  // 操作可重复数量
  const handleNumChange = (num: number, detail: any) => {
    const { detailId, packageId, adjustPrice, categoryId, categoryName, productId, productName, perquantity, tasteCategoryList } = detail;
    // const { packageId, optionalQuantity, packageContent, packageType } = parentItem;
    let newChoosePackageMap = state.choosePackageMap;
    let newChoosePackageDetailsLengthMap = state.choosePackageDetailsLengthMap;
    let newChoosePackageDetailsMap = state.choosePackageDetailsMap;
    if(isEmpty(tasteCategoryList)) {
      let packdetail = {
        packageId,
        adjustPrice,
        categoryId,
        categoryName,
        perquantity,
        productId,
        productName,
        quantity: num,
        tasteList: state.choosePackageDetailsMap.get(detailId).tasteList
      };
      if (num === 0) {
        newChoosePackageDetailsMap.delete(detailId)
      } else {
        newChoosePackageDetailsMap.set(detailId, packdetail);
      }
      let packagelength = reducePackageLength([...newChoosePackageDetailsMap.values()], packageId);
      if (packagelength === 0) {
        newChoosePackageDetailsLengthMap.delete(packageId);
        newChoosePackageMap.delete(packageId)
      } else {
        newChoosePackageDetailsLengthMap.set(packageId, packagelength);
      }
    } else {
      // 当前detailId的选择总数量
      let length = 0;
      newChoosePackageDetailsMap.get(detailId).forEach((item:any) => {
        length += item.quantity
      });
      if(num > length) {
        let lastItem = newChoosePackageDetailsMap.get(detailId)[newChoosePackageDetailsMap.get(detailId).length -1];
        lastItem = {
          ...lastItem,
          quantity: num
        }
        let arrays = [...newChoosePackageDetailsMap.get(detailId).slice(0, newChoosePackageDetailsMap.get(detailId).length -1), lastItem];
        newChoosePackageDetailsMap.set(detailId, arrays);
        let length = 0;
        newChoosePackageDetailsMap.get(detailId).forEach((item:any) => {
          length += item.quantity
        });
        newChoosePackageDetailsLengthMap.set(packageId, length);//set 当前最新的数量
        
      } else {
        
        // console.log('减 拿到最后一项 - ', newChoosePackageDetailsMap.get(detailId))
        if(num === 0) {
          console.log('要删除这个detail');
          let lastItem = newChoosePackageDetailsMap.get(detailId)[newChoosePackageDetailsMap.get(detailId).length -1];
          let arrays = [];
          if(lastItem.quantity === 1) {
            arrays = [...newChoosePackageDetailsMap.get(detailId).slice(0, newChoosePackageDetailsMap.get(detailId).length -1)];
            console.log('zuihouyige===1', lastItem.quantity, arrays )
          } else {
            console.log('zuihouyige===else', lastItem.quantity)
            lastItem = {
              ...lastItem,
              quantity: num
            }
            arrays = [...newChoosePackageDetailsMap.get(detailId).slice(0, newChoosePackageDetailsMap.get(detailId).length -1), lastItem];
          }
          if(isEmpty(arrays)) {
            newChoosePackageDetailsMap.delete(detailId);
          } else {
            newChoosePackageDetailsMap.set(detailId, arrays);
          }
          // let length = 0;
          // newChoosePackageDetailsMap.get(detailId).forEach((item:any) => {
          //   length += item.quantity
          // });
          // newChoosePackageDetailsLengthMap.set(packageId, length);//set 当前最新的数量
        } else {
          let lastItem = newChoosePackageDetailsMap.get(detailId)[newChoosePackageDetailsMap.get(detailId).length -1];
          let arrays = []
          if(num === 1) {//删除最后一项
            arrays = [...newChoosePackageDetailsMap.get(detailId).slice(0, newChoosePackageDetailsMap.get(detailId).length -1)];

          } else {
            lastItem = {
              ...lastItem,
              quantity: num
            }
            arrays = [...newChoosePackageDetailsMap.get(detailId).slice(0, newChoosePackageDetailsMap.get(detailId).length -1), lastItem];
          }
         
          if(isEmpty(arrays)) {
            newChoosePackageDetailsMap.delete(detailId);
          } else{
            newChoosePackageDetailsMap.set(detailId, arrays);
          }
          let length = 0;
          newChoosePackageDetailsMap.get(detailId).forEach((item:any) => {
            length += item.quantity
          });
          if(length === 0) {
            newChoosePackageDetailsLengthMap.delete(packageId)
          } else {
            newChoosePackageDetailsLengthMap.set(packageId, length);//set 当前最新的数量
          }
        }
       

      }
    }
  

    setState({
      ...state,
      choosePackageDetailsLengthMap: newChoosePackageDetailsLengthMap,
      choosePackageDetailsMap: newChoosePackageDetailsMap
    })
  }

  // 获取加的最大值
  const getMax = (item:any, packdetail: any) => {
    let isArray = Array.isArray(state.choosePackageDetailsMap.get(packdetail.detailId)); 
    let currentQuantity;
    if(isArray) {
      // 所有的相加
      let quantity = 0;
      state.choosePackageDetailsMap.get(packdetail.detailId).forEach((item:any) => {
        quantity += item.quantity
      });
      currentQuantity = quantity;
    } else {
      currentQuantity = Number(state.choosePackageDetailsMap.get(packdetail.detailId).quantity);
    }
    return item.optionalQuantity - Number(state.choosePackageDetailsLengthMap.get(packdetail.packageId)) + currentQuantity;
  }

  const getNumberPickerValue =  (packdetail: any) => {
    let isArray = Array.isArray(state.choosePackageDetailsMap.get(packdetail.detailId)); 
    let currentQuantity;
    if(isArray) {
      let quantity = 0;
      state.choosePackageDetailsMap.get(packdetail.detailId).forEach((item:any) => {
        quantity += item.quantity
      }); 
      currentQuantity = quantity;
    } else {
      currentQuantity = state.choosePackageDetailsMap.get(packdetail.detailId).quantity
    }
    return currentQuantity
  }


  console.log('state', state)
  return <>
    {isEmpty(packageInfo) ? <AsyncLoading /> : <div className={styles.main_pack_wrap}>
      <Header title='套餐選擇' hasBack />
      <div className={styles.picture}>
        <SwiperBox
          ikey="id"
          data={images}
          wrapClass={styles.index_banner}
          dotsClass={styles.banner_dots}
          renderRow={(item: string, index: number) => (
            <Picture
              setRef={swiperRef.current}
              className={styles.pack_banner_item}
              key={index}
              src={item}
            />
          )}
        />
      </div>
      <div className={styles.title_wrap}>
        <h3 className={styles.productName}>{packageInfo?.productName}</h3>
        <p className={styles.packagetDesc}>{packagetDesc.join('+')}</p>
      </div>
      {!isEmpty(packageInfo.productPackages) ? packageInfo.productPackages.map((item: any, index: number) => {
        let selectedDesc = getSelectedDesc(item);
        // let selectedDesc:any = [];

        return (<div className={styles.package_info} key={`${index}_${item.packageId}`}>
          <div className={styles.title}>
            <h3>
              <span>{item.packageContent}{`(${item.packageType === 'M' ? '必選' : '可選'}${item.optionalQuantity})`}</span>
              {/* <span>总共可选『{item.optionalQuantity}』 当前已选『{state.choosePackageDetailsLengthMap.get(item.packageId)}』</span> */}
            </h3>
            {selectedDesc.map((item: any) => <div className={styles.sub_title} key={item}>已選：{item} </div>)}
          </div>

          <ul className={styles.package_wrap}>
            {!isEmpty(item.packageDetails) ? item.packageDetails.map((packdetail: any, index: number) => {
              return <li
                className={`${styles.package_item} 
                ${activeClassName(packdetail, item)}
              `}
                key={`${index}_${packdetail.detailId}`}
                onClick={() => handleClickItem(item, packdetail)}
              >
                {!!(packdetail.quantity > 1) && <span className={styles.quantity}>X{packdetail.quantity}</span>}
                <Picture src={`${packdetail.productIcon1}/600`} className={styles.packdetailImg} />
                <span className={styles.detail_name}>{packdetail.productName}</span>
                <div className={styles.price}><Price price={packdetail.adjustPrice} /></div>
                {/* productStatus === 2 售完 */}
                {packdetail.productStatus === 2 ? <div className={styles.salt_out}>售完</div> : null}
                {/* 激活的情况下，可选数量大于1， 且可重复选 */}
                {item.packageType !== 'M' && state.choosePackageDetailsMap.has(packdetail.detailId) && item.optionalQuantity > 1 && item.optionalRepeat === 'Y' ?
                  <NumberPicker
                    value={getNumberPickerValue(packdetail)}//当前的detail的数量
                    attr={packdetail} onChange={handleNumChange}
                    max={getMax(item, packdetail)}
                  /> : null}
              </li>
            }) : null}
          </ul>
        </div>)
      }) : null}
      <SpecPicker onClose={() => setSpecVisiable(false)} goodsDetail={curentDetailInfo.packdetail} specVisiable={specVisiable} onClickSure={onClickSure} />

      <div className={styles.pay_wrap}>
        <div className={styles.pay_hidden}></div>
        <AffixBottom className={styles.pay_main}>
          {<strong className={styles.real_amount}><Price price={calcPrice()} /></strong>}
          <button type="button" className={styles.pay_button} onClick={handleChooseOk}>已選好</button>
        </AffixBottom>
      </div>
    </div>}

  </>
}